package org.qtk.server;

import java.io.IOException;
import java.net.Socket;

/**
 * 一个请求一个响应 就对应一个此线程
 * 
 * @author SiriusTK
 * 
 */
public class Dispatcher implements Runnable {

	private Request request;
	private Response response;
	private Socket clientSocket;
	private int code = 200;

	public Dispatcher(Socket clientSocket) {
		this.clientSocket = clientSocket;
		try {
			request = new Request(clientSocket.getInputStream());
			response = new Response(clientSocket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
			code = 500;
			return;
		}
	}

	@Override
	public void run() {
		try {
			String servletClz = WebApp.getServlet(request.getUrl());
			Servlet servlet = (Servlet) Class.forName(servletClz).newInstance();
			if (servlet == null) {
				code = 404;
			} else {
				servlet.service(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			code = 500;
		} finally {
			try {
				response.pushToClient(code);
				clientSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
